package org.database.generator.code;

import org.database.generator.code.utils.Configuration;
import org.database.generator.code.utils.FreemarkerUtil;
import org.database.generator.code.utils.IOUtils;
import org.database.generator.code.model.Table;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2019/8/27 10:14
 * @since
 */
public class CodeGenerator {

    TableInspector tableInspector = new TableInspector();

    /**
     * 根据数据库的表名生成相关类
     * 生成文件的路径在项目下的code文件夹下
     * @param tableName 表名
     * @param packageStr 包名
     * @param outFile 输出控制台还是文件，true:文件、false：只控制台打印
     */
    public void create(String tableName, String packageStr, String className, boolean print, boolean outFile){
        Table table = tableInspector.queryTable(tableName);

        if(className != null && !"".equals(className.trim())){
            table.setClassName(className);
            table.setClassNameLower(String.valueOf(className.charAt(0)).toLowerCase() + className.substring(1));
        }

        Map<String, Object> root = new HashMap<>();
        initRootMap(root);
        root.put("table", table);
        root.put("packageStr", packageStr);

        String rootPath = getProjectRootPath();
        String codeRootPath = rootPath.substring(0, rootPath.indexOf("target")) + "code/";

        FreemarkerUtil freemarkerUtil = FreemarkerUtil.getInstance("/template");
        String model = freemarkerUtil.process(root, "Model.java");
        String vo = freemarkerUtil.process(root, "VO.java");
        String mapper = freemarkerUtil.process(root, "Mapper.java");
        String manager = freemarkerUtil.process(root, "Manager.java");
        String controller = freemarkerUtil.process(root, "Controller.java");

        if(print){
            System.out.println(model);
            System.out.println(vo);
            System.out.println(mapper);
            System.out.println(manager);
            System.out.println(controller);
        }

        if(outFile){
            wirteStringToFile(model, codeRootPath + "model/" + table.getClassName() + ".java");
            wirteStringToFile(mapper, codeRootPath + "mapper/" + table.getClassName() + "Mapper.java");
            wirteStringToFile(vo, codeRootPath + "vo/" + table.getClassName() + "VO.java");
            wirteStringToFile(manager, codeRootPath + "manager/" + table.getClassName() + "Manager.java");
            wirteStringToFile(controller, codeRootPath+ "controller/" + table.getClassName() + "Controller.java");
        }
    }

    /**
     * 获取项目根路径
     * @return
     */
    private String getProjectRootPath(){
        String rootPath = this.getClass().getResource("/").getPath(); // /F:/dev/cy-helmet/cy-code-generator/target/test-classes/
        try {
            rootPath = URLDecoder.decode(rootPath,"utf-8"); // 防止中文乱码
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return rootPath;
    }

    private void wirteStringToFile(String content, String filePath){
        File file = new File(filePath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }

        IOUtils.wirteStringToFile(content, file, true);
    }

    private void initRootMap(Map<String, Object> root){
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        root.put("date", df.format(new Date()));

        // 作者
        String author = Configuration.get("cy.author");
        if(author == null || "".equals(author)){
            author = System.getenv().get("COMPUTERNAME");
        }
        root.put("author", author);

        root.put("line", "\n");
    }


}
